/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vehicles;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author jonesbr
 */
public class Driver {

    // Declare an ArrayList that will hold a collection of Cars.
    static ArrayList<Car> allCars = new ArrayList<Car>();
    // a collection of trips.
    static int trips[] = new int[100];
    // companion variable
    static int numberOfTrips = 0;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        System.out.println("In Main.");

        int loadData = JOptionPane.showConfirmDialog(null, "Do you want to load existing data?", "Load Saved Data", JOptionPane.YES_NO_OPTION);
        if (loadData == JOptionPane.YES_OPTION) {
            // load existing data.
            loadData();
        } else {
            // make a method call to promptUser
            promptUser();
        }

        // prompt the user for the trips to take.
        promptForTrips();
        
        // run each car for each trip.
        runCars();

        // write cars to a data file.
        writeCars();
        
    }

    public static void promptUser() {
        System.out.println("In promptUser");
        System.out.println("");

        // declare a variable that will hold the value of the user's response.
        int moreCars;
        
        // prompt for the price of gas.
        String strPriceOfGas = JOptionPane.showInputDialog("What is the price of gas?");
        double dblPriceOfGas = Double.parseDouble(strPriceOfGas);

        // assign the price of gas.
        Car.setPricePerGallon(dblPriceOfGas);

        
        // begin the do loop.
        do {
        
            // Ask the user for a type of car.
            // Declare an array with two elements.
            String carTypes[] = new String[3];
            // assign a value to the first element.
            carTypes[0] = "Neon";
            // assign a value to the second element.
            carTypes[1] = "Prius";
            // make a truck
            carTypes[2] = "Tundra";
            
            // show this to the user
            String strCarType = (String) JOptionPane.showInputDialog(null, "Select a Car", "Pick", JOptionPane.QUESTION_MESSAGE, null, carTypes, carTypes[0]);
            
            Car myCar = createCar(strCarType);
            
            // pass the selected car type to our Car object.
            // myCar.setCarType(strCarType);
            
            String strOdometer = JOptionPane.showInputDialog("What is the odometer?");

            // Convert String data to int data.
            int intOdometer = Integer.parseInt(strOdometer);

            // assign these values to our car.
            myCar.setOdometer(intOdometer);

            // prompt for Trip Odometer.
            String strTripOdometer = JOptionPane.showInputDialog("What is the trip odometer");

            // Convert from String to int.
            int intTripOdometer = Integer.parseInt(strTripOdometer);
            myCar.setTripOdometer(intTripOdometer);

            // prompt for miles per gallon.
            String strMilesPerGallon = JOptionPane.showInputDialog("What are the Miles per Gallon");

            // convert miles per gallon from STring to int and store in the Car.
            int intMilesPerGallon = Integer.parseInt(strMilesPerGallon);
            myCar.setMilesPerGallon(intMilesPerGallon);

            // prompt for gallons of gas.
            String strGallonsOfGas = JOptionPane.showInputDialog("What are the gallons of gas?");

            // convert gallons of gas and store in myCar.
            double dblGallonsOfGas = Double.parseDouble(strGallonsOfGas);
            myCar.setGallonsOfGas(dblGallonsOfGas);

            // add the created car to our parking garage of cars (the ArrayList)
            allCars.add(myCar);

            // ask the user if he or she wishes to go again.
            moreCars = JOptionPane.showConfirmDialog(null, "Do you want to add another car?", "Add another car?", JOptionPane.YES_NO_OPTION);

            // see if the user chose yes.  If the user chose yes, go again.
        } while (moreCars == JOptionPane.YES_OPTION);

//        // print the before state.
//        System.out.println("My Car: " + myCar.toString());
//        
//        // convert from String to int
//        int intDistance = Integer.parseInt(strDistance);
//        myCar.go(intDistance);
//        
//        // run my car, not your car.
//        System.out.println("My Car: " + myCar.toString());
//
//        // print the after state.
//        System.out.println("My Car: " + myCar.toString());


    }

    /**
     * Prompt the user for trips to take in the collection of vehicles.
     */
    private static void promptForTrips() {
        // initialize our loop control variable
        boolean goAgain = true;
        while (goAgain) {
            // ask the user how far he/she wants to go.
            String strDistance = JOptionPane.showInputDialog("How far do you want to go?");
            // convert to an int.
            int intDistance = Integer.parseInt(strDistance);
            // store this into our array of trips, using the companion variable to determine the next free space.
            trips[numberOfTrips] = intDistance;
            // advance the trips byt 1.
            numberOfTrips++;

            // see if the user wants to go again.
            int moreTrips = JOptionPane.showConfirmDialog(null, "Do you want to add another trip?", "Add another trip?", JOptionPane.YES_NO_OPTION);

            // if the user said yes, then keep the loop control variable true.    
            if (moreTrips == JOptionPane.NO_OPTION) {
                // otherwise, make the loop control variable false.
                goAgain = false;
            }
        }
    }

    private static void runCars() {
        // iterate over the cars
        for (Car thisCar : allCars) {
            // iterate over the trips./
            for (int i = 0; i < numberOfTrips; i++) {
                // i represents the current iteration of the trips loop.
                // each time this inner loop executes, we will access the next trip in the array.
                int thisTrip = trips[i];
                // apply this trip to the car from the outer loop.
                thisCar.go(thisTrip);
                // print the state of the car after the car has run for this trip.
                System.out.println("State of Car after trip " + thisTrip + " is: " + thisCar.toString());
            }
        }
        
    }

      /**
     * Write cars to a data file.
     */
    private static void writeCars() {

        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            // Create directory for outgoing data.
            File dataDirectory = new File("data" + File.separator + "outgoing");
            // make those directories.
            dataDirectory.mkdirs();
            // Create a data file in the specified directory.
            File dataFile = new File(dataDirectory, "out.txt");
            // create a FileWriter and BufferedWriter.
            fw = new FileWriter(dataFile);
             bw = new BufferedWriter(fw);

            // iterate over the cars, and write each to a file on its own line.
            for (Car car : allCars) {
                bw.write(car.convertToString());
//                bw.newLine();
            }

        
        } catch (IOException ex) {
            // handle exception.  Log and notify user.
            Logger.getLogger(Driver.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, "There was an error writing to the file.");
        } finally {
            try {
                // close the file writer.
                bw.close();
                fw.close();
            } catch (IOException ex) {
                Logger.getLogger(Driver.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    public static Car createCar(String strCarType) {
        // create a car object to store our values.
        // Declare a variable of type Car, named myCar.
        // initialize the Car variable by calling the constructor.
        Car myCar = null;
        // create an Object type based on what the user selected.
        if (strCarType.equals("Neon")) {
            // initialize myCar to a Neon object
            myCar = new Neon();
        } else if (strCarType.equals("Prius")) {
            Prius myPrius = new Prius();
            myCar = myPrius;
        } else if (strCarType.equals("Tundra")) {
            myCar = new Tundra();
        }
        return myCar;
    }

    /**
     * Load data from a file.
     */
    private static void loadData() {
            // Create directory for outgoing data.
            File dataDirectory = new File("data" + File.separator + "outgoing");
            // make those directories.
            dataDirectory.mkdirs();
            // Create a data file in the specified directory.
            File dataFile = new File(dataDirectory, "out.txt");
        try {            
            Scanner myScanner = new Scanner(dataFile);
            // while there are still lines to read...
            while(myScanner.hasNextLine()) {
                
                // read a line.
                String data = myScanner.nextLine();
                
                // pass the data to our Car class to create and populate a new car.
                Car myCar = Car.convertFromString(data);
                
                // add this car to our ArrayList.
                allCars.add(myCar);
            }
            
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Driver.class.getName()).log(Level.SEVERE, null, ex);
        }
            
            
    }
}
